#-*-coding=utf8-*-
'''
Created on 2014年5月8日

@author: george
'''

import email
import imaplib



def _extract_body(payload):   
    if isinstance(payload,str):   
        return payload   
    else:   
        return '\n'.join([_extract_body(part.get_payload()) for part in payload])

class Email_Receiver(object):
    
    def __init__(self,mail_server,username,password,ssl=False):
        
        if ssl:
            self.client = imaplib.IMAP4(mail_server)
        else:
            self.client = imaplib.IMAP4(mail_server)
        self.client.login(username, password)
        
        
    def receive_new(self):
        """receive all new mails
        """
        self.client.select()
        res,items = self.client.search(None,'RECENT')

        if res == 'OK' and items[0]:
            _items = items[0].split()
            return [self._get_subject_and_body(i) for i in _items]
            
            
    def _get_subject_and_body(self,item):
        res,data = self.client.fetch(item, "(RFC822)")
        
        subject = ''
        body = ''
        sender = ''
        if res == 'OK':
            mail = email.message_from_string(data[0][1])
            subject = mail['subject']
            sender = mail['From']
            body= mail.get_payload()
        
        return subject,_extract_body(body),sender
    
    def __del__(self):
        self.client.close()
        self.client.logout()


if __name__ == "__main__":
    mail_server = "imap.163.com"
    user = 'gongjun0208@163.com'
    password = 'g-1812998535'

    
    rev = Email_Receiver(mail_server,user,password)
    print rev._get_subject_and_body('3')